package com.ruoyi.generator.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.generator.entity.PlanItemType;
import com.ruoyi.generator.entity.PlanSchedule;
import com.ruoyi.generator.entity.PlanScheduleHistory;
import com.ruoyi.generator.entity.UserMsg;
import com.ruoyi.generator.entity.bo.PlanScheduleAreaBO;
import com.ruoyi.generator.entity.bo.PlanScheduleCountBo;
import com.ruoyi.generator.entity.bo.PlanScheduleInfoBO;
import com.ruoyi.generator.entity.bo.PlanScheduleStaticInfoBO;
import com.ruoyi.generator.mapper.PlanScheduleHistoryMapper;
import com.ruoyi.generator.mapper.PlanScheduleMapper;
import com.ruoyi.generator.mapper.UserMsgMapper;
import com.ruoyi.generator.service.PlanScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.generator.util.JiSuanUtil.checkTimeStatus;
import static com.ruoyi.generator.util.JiSuanUtil.isCurrentTimeInRange;
import static java.time.LocalDateTime.now;

/**
 * 点检计划周期状态信息 服务层处理
 */
@Service
public class PlanScheduleServiceImpl implements PlanScheduleService {

    @Autowired
    private PlanScheduleMapper planScheduleMapper;

    @Autowired
    private UserMsgMapper userMsgMapper;

    @Autowired
    private PlanScheduleHistoryMapper planScheduleHistoryMapper;

    /**
     * 获取点检计划与周期状态信息列表
     *
     * @param planSchedule
     * @return
     */
    @Transactional
    @Override
    public List<PlanScheduleInfoBO> getPlanScheduleList(PlanSchedule planSchedule) {
        List<PlanScheduleInfoBO> planScheduleInfoBOList = planScheduleMapper.selectPlanScheduleList(planSchedule);

//        //获取当前时间
//        LocalDateTime now = LocalDateTime.now();
//        // 定义时间格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
//        // 格式化当前时间
//        String formattedTime = now.format(formatter);
//        // 字符串转LocalDateTime
//        LocalTime timem = LocalTime.parse(formattedTime, formatter);
//        // 提取分钟值
//        Integer minutes = timem.getHour() * 60 + timem.getMinute();
//
//        PlanSchedule planSchedule1 = new PlanSchedule();
//        editPlanScheduleInfoStatus(planSchedule1);
//        for (PlanScheduleInfoBO planScheduleInfoBO : planScheduleInfoBOList) {
//            if (planScheduleInfoBO.getCheckStatus().equals("运行中")) {
//                if (planScheduleInfoBO.getTime().contains("当日")) {
//                    //结束时间
//                    LocalTime editTime = LocalTime.parse(planScheduleInfoBO.getTime().substring(planScheduleInfoBO.getTime().length() - 5),formatter);
//                    // 提取分钟值
//                    Integer editMinutes = editTime.getHour() * 60 + editTime.getMinute();
//
//                    //新增历史数据
//                    PlanScheduleHistory planScheduleHistory = new PlanScheduleHistory();
//                    planScheduleHistory.setPlanScheduleId(Long.valueOf(planScheduleInfoBO.getPlanScheduleId()));
//                    planScheduleHistory.setPlanAssociationId(Long.valueOf(planScheduleInfoBO.getPlanAssociationId()));
//                    planScheduleHistory.setScheduleId(Long.valueOf(planScheduleInfoBO.getScheduleId()));
//                    planScheduleHistory.setPeriod(planScheduleInfoBO.getPeriod());
//                    planScheduleHistory.setShiftDefaultId(Long.valueOf(planScheduleInfoBO.getShiftDefaultId()));
//
//                    //开始时间对比当前时间
//                    if (minutes > editMinutes) {
//                        //修改状态为已过期
//                        planSchedule1.setPlanScheduleId(planScheduleInfoBO.getPlanScheduleId());
//                        planSchedule1.setCheckStatus("已过期");
//                        planScheduleMapper.updatePlanSchedule(planSchedule1);
//
//                        //新增历史数据
//                        planScheduleHistory.setCheckStatus(planSchedule1.getCheckStatus());
//                        planScheduleHistory.setCreateTime(LocalDate.from(now));
//                        planScheduleHistoryMapper.insertPlanScheduleHistory(planScheduleHistory);
//                    }
//                }
//            }
//        }
        return planScheduleInfoBOList;
    }

    @Override
    public List<PlanScheduleStaticInfoBO> getPlanScheduleStaticList(PlanScheduleStaticInfoBO planSchedule) {
        if(planSchedule.getCheckStatus()!=null && planSchedule.getCheckStatus().equals("未完成")){
            planSchedule.setCheckStatus("未开始");
            planSchedule.setStatus("运行中");
        }
        List<PlanScheduleStaticInfoBO> planScheduleInfoBOList=new ArrayList<PlanScheduleStaticInfoBO>();
        if(planSchedule.getStartDate()!=null || planSchedule.getEndDate()!=null){
             planScheduleInfoBOList = planScheduleMapper.selectPlanScheduleStaticListHistory(planSchedule);
        }else{
             planScheduleInfoBOList = planScheduleMapper.selectPlanScheduleStaticList(planSchedule);
        }
        return planScheduleInfoBOList;
    }

    @Override
    public List<PlanScheduleAreaBO> selectPlanScheduleArea() {
        List<PlanScheduleAreaBO> planScheduleInfoBOList = planScheduleMapper.selectPlanScheduleArea();
        return planScheduleInfoBOList;
    }
    @Override
    public List<PlanScheduleCountBo> selectPlanScheduleCount() {
        List<PlanScheduleCountBo> planScheduleInfoBOList = planScheduleMapper.selectPlanScheduleCount();
        return planScheduleInfoBOList;
    }


    @Transactional
    public void editPlanScheduleInfoStatus(PlanSchedule planSchedule){
        planSchedule.setCheckStatus("未开始");
        List<PlanScheduleInfoBO> planScheduleInfoBOListStatus = planScheduleMapper.selectPlanScheduleList(planSchedule);
        //获取当前时间
        LocalDateTime now = now();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        // 格式化当前时间
        String formattedTime = now.format(formatter);
        // 字符串转LocalDateTime
        LocalTime timem = LocalTime.parse(formattedTime, formatter);
        // 提取分钟值
        Integer minutes = timem.getHour() * 60 + timem.getMinute();
        for (PlanScheduleInfoBO planScheduleInfoBO : planScheduleInfoBOListStatus) {
            if (planScheduleInfoBO.getTime().contains("当日")) {
                //新增历史数据
                PlanScheduleHistory planScheduleHistory = new PlanScheduleHistory();
                planScheduleHistory.setPlanScheduleId(Long.valueOf(planScheduleInfoBO.getPlanScheduleId()));
                planScheduleHistory.setPlanAssociationId(Long.valueOf(planScheduleInfoBO.getPlanAssociationId()));
                planScheduleHistory.setScheduleId(Long.valueOf(planScheduleInfoBO.getScheduleId()));
                planScheduleHistory.setPeriod(planScheduleInfoBO.getPeriod());
                planScheduleHistory.setShiftDefaultId(Long.valueOf(planScheduleInfoBO.getShiftDefaultId()));

                //结束时间
                LocalTime editTime = LocalTime.parse(planScheduleInfoBO.getTime().substring(planScheduleInfoBO.getTime().length() - 5),formatter);
                //开始时间
                LocalTime endTime = LocalTime.parse(planScheduleInfoBO.getTime().substring(2, 7),formatter);
                // 提取分钟值
                Integer editMinutes = editTime.getHour() * 60 + editTime.getMinute();
                Integer endMinutes = endTime.getHour() * 60 + endTime.getMinute();
                //开始时间对比当前时间
                if (minutes > endMinutes && minutes < editMinutes) {
                    //修改状态为运行中
                    planSchedule.setPlanScheduleId(planScheduleInfoBO.getPlanScheduleId());
                    planSchedule.setCheckStatus("运行中");
                    planScheduleMapper.updatePlanSchedule(planSchedule);
                }
                if (minutes > editMinutes) {
                    //修改状态为已过期
                    planSchedule.setPlanScheduleId(planScheduleInfoBO.getPlanScheduleId());
                    planSchedule.setCheckStatus("已过期");
                    planScheduleMapper.updatePlanSchedule(planSchedule);

                    //新增历史数据
                    planScheduleHistory.setCheckStatus(planSchedule.getCheckStatus());
                    planScheduleHistory.setCreateTime(LocalDate.from(now));
                    planScheduleHistoryMapper.insertPlanScheduleHistory(planScheduleHistory);
                }
            }
        }
    }


    @Override
    public void updatePlanScheduleStatus(Integer planScheduleId) {
        planScheduleMapper.updatePlanScheduleStatus(planScheduleId);
    }

    @Transactional
    @Override
    public void updatePlanSchedule(PlanSchedule planSchedule) {
        PlanSchedule planSchedule1 = planScheduleMapper.selectPlanScheduleById(planSchedule.getPlanScheduleId());
        //新增点检历史
        PlanScheduleHistory planScheduleHistory = new PlanScheduleHistory();
        planScheduleHistory.setPlanScheduleId(Long.valueOf(planSchedule1.getPlanScheduleId()));
        planScheduleHistory.setPlanAssociationId(Long.valueOf(planSchedule1.getPlanAssociationId()));
        planScheduleHistory.setScheduleId(Long.valueOf(planSchedule1.getScheduleId()));
        planScheduleHistory.setPeriod(planSchedule1.getPeriod());
        planScheduleHistory.setShiftDefaultId(Long.valueOf(planSchedule1.getShiftDefaultId()));
        planScheduleHistory.setCreateTime(LocalDate.now());
        if (planSchedule.getDeviceStatus().equals("正常")) {
            planSchedule.setCheckStatus("已完成");
            planScheduleMapper.updatePlanSchedule(planSchedule);
            planScheduleHistory.setCheckStatus("已完成");
            planScheduleHistory.setDeviceStatus(planSchedule.getDeviceStatus());
            planScheduleHistory.setRemark(planSchedule.getRemark());
            planScheduleHistoryMapper.insertPlanScheduleHistory(planScheduleHistory);
        } else {
            planSchedule.setCheckStatus("已完成");
            planScheduleMapper.updatePlanSchedule(planSchedule);
        }
        if (!planSchedule.getDeviceStatus().equals("正常")) {
            UserMsg userMsg = new UserMsg();
            userMsg.setCreateTime(now());
            userMsg.setIsDeleted(false);
            userMsg.setJumpPath("/work-order");
            userMsg.setTaskNumber(String.valueOf(planSchedule1.getPlanAssociationId()));
            //获取当前登录人id
            String createBy = SecurityUtils.getUsername();
            userMsg.setUserId(Math.toIntExact(getUserId()));
            userMsg.setMessage("周期id："+planSchedule1.getPlanScheduleId()+"，计划id："+planSchedule1.getPlanAssociationId()+"，设备状态："+planSchedule.getDeviceStatus()+"，发现问题时间"+now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"，问题描述："+planSchedule.getRemark()+"，发现人："+createBy);
            userMsgMapper.addMsg(userMsg);
        }

    }


    //查询点检项和设备名称
    public List<PlanItemType> selectEquipmentTypeList(){
       return  planScheduleMapper.selectEquipmentTypeList();
    };
    public List<PlanItemType>  selectCheckItemList(){
        return  planScheduleMapper.selectCheckItemList();
    };


}
